package com.ctl.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ctl.entity.Admin;
import com.ctl.service.AdminService;
import com.ctl.service.RedisTokenPrefix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
//@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService service;

    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/tokens")
    public Map<String,String> login(@RequestBody Admin admin){
        Map<String, String> map = new HashMap<>();
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",admin.getUsername());
        Admin admindb = service.getOne(queryWrapper);
        //判断数据是否存在该用户
        if (admindb==null){
            throw new RuntimeException("用户名错误！");
        }
        //存在该用户，则对密码加密
       String password =DigestUtils.md5DigestAsHex(admin.getPassword().getBytes());
        if (password.equals(admindb.getPassword())){
            String uuid = UUID.randomUUID().toString();
                //添加token登录令牌Redis_Token_Prefix
            redisTemplate.opsForValue().set(RedisTokenPrefix.Redis_Token_Prefix +uuid,admindb,1, TimeUnit.HOURS);
            map.put("token",RedisTokenPrefix.Redis_Token_Prefix+uuid);
        }
        return map;
    }
    @DeleteMapping("/tokens/{token}")
    public String logout(@PathVariable String token){
        redisTemplate.delete(token);
        return "ok";
    }
    @GetMapping("/admin-user")
    public Map<String,String> userDatils(String token){
        Admin admin = (Admin) redisTemplate.opsForValue().get(token);
        Map<String, String> map = new HashMap<>();
        map.put("name",admin.getUsername());
        map.put("avatar",admin.getAvatar());
        return map;
    }



}
